﻿using System;
using Shell.PocoDot;

namespace Shell.DomainDot
{
    public class Main<TPocoDot> : IDisposable
        where TPocoDot : PocoDotBase
    {
        private bool disposed;
        private object syncroot;

        public Main(Guid key, IDataContext<TPocoDot> repository)
        {
            this.syncroot = new object();
            this.IsInitialized = false;
            this.Key = key;
            this.Repository = repository;
        }

        protected Guid Key { get; private set; }

        protected IDataContext<TPocoDot> Repository { get; private set; }

        protected bool IsInitialized { get; private set; }

        protected TPocoDot LazyInstance { get; set; }

        public TPocoDot Instance
        {
            get
            {
                if (!this.IsInitialized)
                {
                    lock (this.syncroot)
                    {
                        if (!this.IsInitialized)
                        {
                            this.Initialize();
                        }
                    }
                }
                return this.LazyInstance;
            }
        }

        public int Submit()
        {
            return this.Repository.Submit();
        }

        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (!this.disposed)
                {
                    this.Repository = null;
                }
                this.disposed = true;
            }
        }

        protected virtual void Initialize()
        {
            this.LazyInstance = this.Repository.Read(this.Key);
            this.IsInitialized = true;
        }
    }
}
